package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName HelloController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/13
 * @Version 1.0
 */
@Controller
public class HelloController {

    /**
     * 无需登录即可访问
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token){
        if(!StringUtils.isEmpty(token)){
            //查询真正的数据
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/getInfo?token="+token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("emps",body);
        }
        Object empsOb = session.getAttribute("emps");
        if(empsOb == null){
            //未登录跳转到登录页
            return "redirect:http://ssoserver.com:8080/login.html"+"?redirect_url=http://client1.com:8085/employees";
        }else {
            //登录则跳转到展示页
            List<String> emps=new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps",emps);
            return "emps";
        }

    }
}
